local filelog = require "filelog"
local skynet = require "skynet"
local math_random = math.random

local bulletid = 0
local tablelogic, gamelogic
local robot = {}

function robot:new(obj)
	local entity = obj or {shootenable = false, angle = math_random(-75, 75)}
	setmetatable(entity, self)
	self.__index = self
	return entity
end

function robot:shoot(seat)
	if self.isenable and self.shootenable then
		bulletid = bulletid + 1
		-- gamelogic.shoot(seat.rid, bulletid, math_random(-75, 75), seat.shootlevel)
		gamelogic.shoot(seat.rid, bulletid, self.angle, seat.shootlevel)
	end
end

function robot:analyse(table_data, seat)
	if not self.isenable then return end
	if seat.diamond < seat.launcher.Point * (seat.shootlevel or 1) then
		tablelogic.passive_standuptable(table_data, seat)
		return
	else
		skynet.sleep(35, 50)
		self:shoot(seat)
		if seat.shootstat ~= 1 then
			if math_random(100) <= 5 then
				self:set_angle(math_random(-75, 75))
			end
		end
		pcall(self.analyse, self, table_data, seat)
	end
end

local function timetrigger(self, table_data, seat)
	if not self.isenable then return end
	local rand = math_random(5)
	if rand == 2 then
		if seat.shootstat ~= 1 then
			self:set_angle(math_random(-75, 75))
		end
		print("robot timetrigger: set angle")
	elseif rand == 3 then
		if math_random(0, 1) == 0 then
			tablelogic.upgradeshoot(table_data, seat, {level = 1})
		else
			tablelogic.upgradeshoot(table_data, seat, {level = -1})
		end
		print("robot timetrigger: set shootlevel")
	elseif rand == 4 then
		tablelogic.useitem(table_data, seat, seat.items[1], 1)
		skynet.timeout(math_random(5, 10) * 100, function()
			if not self.isenable then return end
			tablelogic.useitem(table_data, seat, seat.items[1], 1)
		end)
		print("robot timetrigger: set locktarget")
	elseif rand == 5 then
		self:set_shootenable()
		skynet.timeout(math_random(3, 5) * 100, function()
			if not self.isenable then return end
			self:set_shootenable(true)
		end)
		print("robot timetrigger: set shootenable")
	end
end

function robot:auto(table_data, seat)
	skynet.fork(function()
		while true do
			-- print("robot isenable = ", self.isenable)
			-- skynet.sleep(math_random(10, 15) * 100)
			skynet.sleep(math_random(20, 30) * 100)
            if self.isenable then
				pcall(timetrigger, self, table_data, seat)
			else
				break
            end
        end
	end)

	self:analyse(table_data, seat)
end

function robot:set_enable(isenable)
	self.isenable = isenable
end

function robot:set_angle(angle)
	self.angle = angle
end

function robot:set_shootenable(isenable)
	self.shootenable = isenable
end

function robot:init(tlogic, glogic)
	tablelogic = tlogic
	gamelogic = glogic
	self:set_enable(true)
	self:set_shootenable(true)
end

return robot
